package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.db.User;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.Video;
import com.tanhua.dubbo.utils.IdService;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Video video) {
        video.setId(new ObjectId());
        video.setVid(idService.getNextId("video")); //大数据推送时需要的一个id
        video.setCreated(new Date().getTime());
        mongoTemplate.save(video);
    }

    @Override
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        Query query = new Query();
        query.with(PageRequest.of(page-1,pagesize, Sort.by(Sort.Direction.DESC,"created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        return new PageResult(page,pagesize,(int)count,videoList);
    }

    @Override  //保存关注用户数据
    public void saveFollowUser(Long userId, Long followUserId) {
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);
        followUser.setFollowUserId(followUserId);
        followUser.setId(new ObjectId());
        followUser.setCreated(new Date().getTime());
        mongoTemplate.save(followUser);
    }

    @Override
    public void removeFollowUser(Long userId, Long followUserId) {
//        userId    followUserId
        Query query = new Query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId)) ;
         mongoTemplate.remove(query,FollowUser.class);

    }

    @Override
    public PageResult queryVideosByUserId(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(PageRequest.of(page-1,pagesize, Sort.by(Sort.Direction.DESC,"created")));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        return new PageResult(page,pagesize,(int)count,videoList);
    }

    @Override
    public Publish findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Publish.class);
    }


}
